package org.example.test_zhanbao_chaibao;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.nio.charset.Charset;


//netty服务器
public class MyServer {

    public static void main(String[] args) throws InterruptedException {
        //两个事件循环组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(); // 默认线程数 = CPU核心数 * 2

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)//serverSocketChannel类型
                    .childHandler(new ChannelInitializer<SocketChannel>() { //子处理器  是SocketChannel类型
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 获取管道
                            ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new StarDelimiterFrameDecoder());
                            pipeline.addLast(new StringDecoder(Charset.forName("UTF-8")));

                            // 自定义业务处理器
                            pipeline.addLast(new MyServerHandler());
                        }
                    });

            ChannelFuture future = bootstrap.bind(7001).sync();
            System.out.println("服务器启动成功");
            future.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}